<template>
	<view class=''>
		<navigation-custom title="壁纸圈" ref="titleRef"></navigation-custom>
		
		<view class="topBox" :style="{
			marginTop:`-${getNavBarHeight()}px`,
			paddingTop: getNavBarHeight()+'px'
		}" ref="topBoxRef">
			<view class="searchBarBox">
				<uni-search-bar @cancel="searchCancel"	 @confirm="searchConfirm"  v-model.trim="searchValue" 
					ref="searchRef" placeholder="搜索" bgColor="transparent" textColor="#fff"
					radius="50"
				>
				</uni-search-bar>
			</view>
			<uni-segmented-control :current="current" :values="items" @clickItem="onClickItem" styleType="text"
				activeColor="#32DBBA"></uni-segmented-control>
		</view>
		
		<float-bar :delBtnIsShow="false" :customItem="customItem"></float-bar>
		<view class="afterbox" :style="{height:`${afterHeight - getNavBarHeight()}px`}" ref="afterboxRef"></view>
		<view class="content">
			<!-- 竖屏图片 -->
			<view v-if="current === 0" class="imageBox s">
				<view class="imageItem" v-for="(item, index) in sList" :key="item._id">
					<image  @click="goToPreview($event, index, sList, 'image')"
					lazy-load mode="aspectFill" :src="item.url"></image>
				</view>
			</view>
			<uni-load-more v-if="current === 0" :status="sList.length === 0 || noData[1] ? 'noMore' : 'more'"></uni-load-more>
			<!-- 横屏图片 -->
			<view v-if="current === 1" class="imageBox h">
				<view class="imageItem" v-for="(item, index) in hList" :key="item._id">
					<image @click="goToPreview($event, index, hList, 'image')"
					lazy-load mode="aspectFill" :src="item.url"></image>
				</view>
			</view>
			<uni-load-more v-if="current === 1" :status="hList.length === 0 || noData[0] ? 'noMore' : 'more'"></uni-load-more>
		</view>
	</view>
	
</template>

<script setup>
	import { getStatusBarHeight,getTitleBarHeight,getNavBarHeight,getLeftIconLeft } from "@/utils/system.js"
	import { ref, reactive, getCurrentInstance } from 'vue'
	import { setTabBarBadge } from '@/utils/client.js'
	import {
		onShow, onReady, onPullDownRefresh, onReachBottom, onPageScroll
	} from '@dcloudio/uni-app'
	import { publicCloudUrlToHttpUrl } from '@/utils/common.js'
	import goToPreview from '@/utils/goToPreview.js'
	onShow(() => {
		setTabBarBadge()
	})
	const scrollTops = ref([0, 0])
	onPageScroll((e) => {
		scrollTops.value[current.value] = e.scrollTop
	})
	// const customItem = ref([{
	// 	callback: () => {
	// 		goToMyList()
	// 	},
	// 	type: 'list',
	// 	status: true
	// },{
	// 	callback: () => {
	// 		addWallpaper()
	// 	},
	// 	type: 'plusempty',
	// 	status: true
	// }])
	// 获取菜单数据
	const customItem = ref([])
	const db = uniCloud.database();
	const communityBarCollection =  db.collection('wallpaper-communityBar');
	const getCustomItem = async () => {
		const res = await communityBarCollection.get()
		// console.log(res.result.data);
		customItem.value = res.result.data
		customItem.value.map(async (item,index)=>{
			item.callback = callbacks[item.sign]
		})
	}
	getCustomItem()
	const callbacks = {
		community_add: ()=>{
			uni.navigateTo({
				url: '/pages/community/wallpaperAdd'
			})
		},
		community_mylist: ()=>{
			uni.navigateTo({
				url: '/pages/community/wallpaperList'
			})
			
		}
	}
	// 搜索
	const searchValue = ref('')
	const searchConfirm = ()=>{
		const fxmap = {
			0: 1,
			1: 0
		}
		const fx = fxmap[current.value]
		init()
		getList(0, countObj[0], ++pageObj.value[0])
		getList(1, countObj[1], ++pageObj.value[1])
	}
	const searchCancel = async () => {
		init()
		scrollTops.value = [0, 0]
		searchValue.value = ''
		await getList(0, countObj[0], ++pageObj.value[0])
		await getList(1, countObj[1], ++pageObj.value[1])
	}
	
	// 标题高度
	const titleRef = ref(null)
	const searchRef = ref(null)
	const afterboxRef = ref(null)
	const topBoxRef = ref(null)
	
	const afterHeight = ref(0)
	onReady(()=>{
		// #ifdef WEB || APP-PLUS
		afterHeight.value = topBoxRef.value.$el.offsetHeight
		// #endif
		
		// #ifdef MP-WEIXIN
		const instance = getCurrentInstance();
		const query = uni.createSelectorQuery().in(instance.proxy);
		query.select(".topBox").boundingClientRect((data) => {
		    // console.log(data.height);
			afterHeight.value = data.height
		  }).exec();
		// #endif
	})
	
	// 分段器
	const items = ['竖屏壁纸', '横屏壁纸']
	const current = ref(0)
	// 切换分段器
	const onClickItem = (e) => {
		if (current.value != e.currentIndex) {
			current.value = e.currentIndex;
		}
		setTimeout(()=>{
			uni.pageScrollTo({
				scrollTop: scrollTops.value[current.value],
				duration: 0
			})
		},0)
	}
	
	const hList = ref([])
	const sList = ref([])
	const noData = ref({
		0: false,
		1: false
	})
	// 0横 1竖
	const pageObj = ref({
		0: 0,
		1: 0
	})
	const countObj = {
		0: 5,
		1: 8
	}
	const userShareCollection = db.collection('wallpaper-userShare');
	const getList = async (fx, count, page) => {
		if (noData.value[fx] == true){
			 return
		}
		uni.showLoading({
			title: "加载中..."
		})
		
		let wereStr = ''
		if(searchValue.value != ''){
			wereStr = wereStr + `&& ${new RegExp(searchValue.value, 'i')}.test(desc) `
		}
		
		try{
			// console.log(`每页${count}条, 第${page}页, 跳过${(page - 1) * count}`);
			const res = await userShareCollection.where(`status == 1 && direction == ${fx} ${wereStr}`)
			.limit(count).skip((page - 1) * count)
			.get()
			if(res.result.data.length < countObj[fx]){
				noData.value[fx] = true
			}
			let dataArr = res.result.data.map(item => {
				return {
					...item,
					cloudUrl: item.url,
					url: publicCloudUrlToHttpUrl(item.url)
				}
			})
			if(fx == 1){
				sList.value = [...sList.value, ...dataArr]
				// console.log('s',sList.value);
			}else if(fx == 0){
				hList.value = [...hList.value, ...dataArr]
				// console.log('h',hList.value);
			}
		}catch(e){

		}finally{
			uni.hideLoading()
		}
		
	}
	getList(0, countObj[0], ++pageObj.value[0])
	getList(1, countObj[1], ++pageObj.value[1])
	
	// 初始化数据
	const init = () => {
		pageObj.value = {
			0: 0,
			1: 0
		}
		noData.value = {
			0: false,
			1: false
		}
		sList.value = []
		hList.value = []
	}
	// 下拉刷新
	onPullDownRefresh(async () => {
		try{
			init()
			await getList(0, countObj[0], ++pageObj.value[0])
			await getList(1, countObj[1], ++pageObj.value[1])
		}catch(e){
			//TODO handle the exception
		}finally{
			// 下拉刷新需要手动关闭
			uni.stopPullDownRefresh()
		}
	
	})
	// 加载更多
	onReachBottom(() => {
		// 因为分段器ui相反的, 竖是0, 横是1, 而请求数据是竖是1, 横是0, 所以映射一下方便取
		const fxmap = {
			0: 1,
			1: 0
		}
		const fx = fxmap[current.value]
		getList(fx, countObj[fx], ++pageObj.value[fx])
	})
</script>

<style lang="scss" scoped>
	.topBox {
		width: 100vw;
		position: fixed;
		z-index: 2;
		background:
		linear-gradient(to bottom,transparent,#fff 700rpx),
		linear-gradient(to right,#32DBBA 15%, #13C4A3 85%,#32DBBA);
		
		.bgClass{
			min-height: 0rpx!important;
		}
		.searchBarBox{
			height: fit-content;
			width: 100%;
			// background: linear-gradient(to bottom, transparent, #fff 700rpx), 
			// linear-gradient(to right, #32DBBA 15%, #13C4A3 85%, #32DBBA);
		}
		:deep(){
			// .uni-searchbar{
			// }
			.uni-searchbar__box{
				border: #fff 1rpx solid!important;
			}
			.segmented-control{
				background-color:#fff;
			}
			.uni-icons,.uni-searchbar__text-placeholder,.uniui-clear,.uni-searchbar__cancel{
				color: #fff!important;
			}
			.uni-input-placeholder{
				color: #fff!important;
				
			}
		}
	
	}
	.fixedBox {
		position: fixed;
		right: 20rpx;
		bottom: 200rpx;
		z-index: 10;
	
		.fixedItem {
			background-color: $theme-bg-color2;
			width: 120rpx;
			height: 120rpx;
			border-radius: 50%;
			display: flex;
			justify-content: center;
			/* 水平居中 */
			align-items: center;
			/* 垂直居中 */
			box-sizing: border-box;
			margin-bottom: 30rpx;
			position: relative;
			box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.2);
		}
	
	}
	.s {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
	
		// justify-items: center;
		.imageItem {
			// 332*514
			// width: 332rpx;
			height: 514rpx;
			// padding: 10rpx;
			margin: 10rpx;
			box-sizing: border-box;
	
			.mask {
				width: calc(100% - 40rpx);
				height: calc(100% - 30rpx);
			}
	
			image {
				width: 100%;
				height: 100%;
			}
		}
	}
	
	.h {
		display: grid;
		grid-template-columns: repeat(1, 1fr);
		justify-items: center;
	
		.imageItem {
			// padding: 5rpx 10rpx;
			margin: 5rpx 10rpx;
			box-sizing: border-box;
			width: 100%;
			height: 420rpx;
	
			.mask {
				width: calc(100% - 40rpx);
				height: calc(100% - 20rpx);
			}
	
			image {
				height: 100%;
				width: 100%;
			}
	
			video {
				height: 100%;
				width: 100%;
			}
		}
	}
	.imageBox {
		width: 730rpx;
		margin: 0 auto;
		padding-top: 20rpx;
	
		.imageItem {
			position: relative;
			overflow: hidden;
	
			.mask {
				// padding: 5rpx 10rpx;
				width: 100%;
				height: 100%;
				display: flex;
				align-items: center;
				justify-content: center;
				position: absolute;
				z-index: 10;
				background-color: rgba(50, 219, 186, 0.5);
				border-radius: 15rpx;
				// 过渡
				transition: all 0.3s;
	
			}
	
			image {
				border-radius: 15rpx;
			}
	
			video {
				width: 100%;
				border-radius: 15rpx;
			}
		}
	}
</style>
